<template>
  <div>
    <van-dropdown-menu active-color="#13C2C2">
      <van-dropdown-item @change="changeStageType" :title="value1?option1[value1].text:'阶段分类'" v-model="value1" :options="option1"></van-dropdown-item>
      <van-dropdown-item @change="changeChannel" :title="value2?option2[value2].text:'客源渠道'" v-model="value2" :options="option2"></van-dropdown-item>
      <van-dropdown-item @change="changeCreateBy" :title="queryParam.inviteCustomerService||'邀约客服'" v-model="queryParam.inviteCustomerService" :options="option3">
      </van-dropdown-item>
      <van-dropdown-item @change="changeProgress" :title="value4?cacheProgressList[value4].itemText:'当前进展'" v-model="value4" :options="progressList">

      </van-dropdown-item>
      <van-dropdown-item @change="changeAddDate" :title="value5?addDateList[value5].itemText:'添加时间'"
       v-model="value5" :options="addDateList"></van-dropdown-item>
      <van-dropdown-item @change="changeFollow" :title="value6?followDateList[value6].itemText:'跟进时间'"
       v-model="value6" :options="followDateList"></van-dropdown-item>
      <van-dropdown-item @change="changeFact" :title="value7?factDateList[value7].itemText:'到店时间'"
       v-model="value7" :options="factDateList"></van-dropdown-item>
    </van-dropdown-menu>
    <a-card :bordered="false">
      <div style="overflow-x: scroll">
        <div v-if="showConditionFlag" style="margin-bottom: 5px;display: flex;width: max-content" >
          当前输入条件：
          <span v-show="this.queryParam.name != null && this.queryParam.name !== ''" style="margin-right: 20px">姓名 / {{this.queryParam.name}}</span>
          <span v-show="this.queryParam.phone != null && this.queryParam.phone !== ''" style="margin-right: 20px">电话 / {{this.queryParam.phone}}</span>
          <span v-show="this.queryParam.address != null && this.queryParam.address !== ''">项目地址 / {{this.queryParam.address}}</span>
        </div>
      </div>
      <van-search placeholder="请选择条件查询" readonly @click="showSearchPopup" style="width: 100%;padding: 0px"/>
      <!-- 查询区域-END -->
      <div class="table-operator">
        <a-button  @click="handleAdd" v-has="'customer:add'" type="primary">新增</a-button>
        <a-button type="primary" v-has="'customer:handover'" @click="handoverCustomer()">交接客户</a-button>
        <a-button  type="primary" @click="resetSearch" >重置</a-button>
      </div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
        selectedRows.length }}</a>项
      </div>
      <div class="list">
        <van-list
          v-model="loading"
          :finished="finished"
          offset="100"
          finished-text="没有更多了"
          @load="onLoadList"
          :immediate-check="false"
        >
          <div
            class="customer-list"
            v-for="(item,i) in dataSource"
            :key="i"
            @click="handleInfoDetail(item.id, item.name)">
            <div>
              <div class="name">{{ item.name }}</div>
              <div class="contact">
                <span>{{ item.phone }}</span>
                <span style="margin-left: 10px;">{{ item.address||'' }}</span>
                <span style="float:right;">
                    <a-checkbox @click.stop="checkClick(item,$event)"></a-checkbox>
                  </span>
              </div>
            </div>
          </div>
        </van-list>
      </div>
      <van-popup v-model="showSearchPopupFlag" position="top" >
        <a-card :bordered="false">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <div>客户姓名：<a-input placeholder="请输入客户姓名" v-model="queryParam.name"></a-input></div>
            <div style="margin-top: 5px">电话：<a-input placeholder="请输入客户电话" v-model="queryParam.phone"></a-input></div>
            <div style="margin-top: 5px">项目地址：<a-input placeholder="请输入项目地址" v-model="queryParam.address"></a-input></div>
            <a-row :gutter="24" style="margin-bottom: 10px;margin-top: 10px">
              <a-col :span="12">
                <a-button type="primary" style="width: 100%" @click="searchQuery" icon="search">查询</a-button>
              </a-col>
              <a-col :span="12">
                <a-button type="primary" @click="resetSearch" icon="reload" style="width: 100%">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
      </van-popup>
    </a-card>
    <gh-customer-info-modal ref="modalForm" @ok="modalFormOk"></gh-customer-info-modal>
    <select-user-modal ref="SelectUserModal" @selectFinished="selectUserOk"></select-user-modal>
  </div>
</template>

<script>
  import '@assets/less/TableExpand.less'
  import { filterObj } from '@/utils/util'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import GhCustomerInfoModal from './modules/GhCustomerInfoModal'
  import { filterDictTextByCache, initDictOptions } from '@comp/dict/JDictSelectUtil'
  import { getAction, postAction, deleteAction, downFile } from '@api/manage'
  import SelectUserModal from './tab/modules/SelectUserModal'
  import Vue from 'vue'
  import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
  import store from '@/store'
  import { mapState, mapMutations } from 'vuex'

  export default {
    name: 'GhCustomerInfoList',
    /*mixins: [JeecgListMixin, mixinDevice],*/
    components: {
      GhCustomerInfoModal, SelectUserModal,
    },
    data() {
      return {
        value1: 0,
        value2: 0,
        value4: 0,
        value5: 0,
        value6: 0,
        value7: 0,
        option1: [
          { text: '全部', value: '0', key: '' },
          { text: '市场阶段', value: '1', key: '1' },
          { text: '设计阶段', value: '2', key: '3' },
          { text: '工程阶段', value: '3', key: '4' },
          { text: '维保阶段', value: '4', key: '5' },
        ],
        option2: [],
        option3: [],
        // option4: [],
        loading: false,
        finished: false,
        progressList: [],
        cacheProgressList: [],
        addDateList: [],
        followDateList: [],
        factDateList: [],
        showConditionFlag: false, //是否显示当前输入的条件值
        description: '客户信息管理页面',
        columns: [],
        defColumns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
            fixed: 'left'
          },
          {
            title: '客户姓名',
            align: 'center',
            dataIndex: 'name',
            slots: { title: 'customTitle' },
            scopedSlots: {
              customRender: 'name'
            },
            fixed: 'left'
          },
          {
            title: '项目地址',
            align: 'center',
            dataIndex: 'address'
          },
          {
            title: '电话',
            align: 'center',
            dataIndex: 'phone'
          },
          {
            title: '最近跟进时间',
            align: 'center',
            dataIndex: 'latelyFollowTime'
          },
          {
            title: '最近跟进内容',
            align: 'center',
            dataIndex: 'latelyFollowContent',
            customCell: () => {
              return {
                style: {
                  wordWrap: 'break-word',
                  wordBreak: 'break-all',
                  whiteSpace: 'normal',
                  minHeight: '50px',
                  width: '700px',
                }
              }
            }
          },
          {
            title: '实际到店时间',
            align: 'center',
            dataIndex: 'factTime'
          },
          {
            title: '客源渠道',
            align: 'center',
            dataIndex: 'customerChannel',
            customRender: (text) => {
              return filterDictTextByCache('customer_info_customer_channel', text)
            }
          },
          {
            title: '邀约客服',
            align: 'center',
            dataIndex: 'inviteCustomerService'
          },
          {
            title: '家装顾问',
            align: 'center',
            dataIndex: 'homeAdviser'
          },
          {
            title: '设计师',
            align: 'center',
            dataIndex: 'designer'
          },
          {
            title: '工程管家',
            align: 'center',
            dataIndex: 'projectKeeper'
          },
          {
            title: '工程监理',
            align: 'center',
            dataIndex: 'projectSupervision'
          },
          {
            title: '预决算员',
            align: 'center',
            dataIndex: 'preFinalAccounts'
          },
          {
            title: '当前进展',
            align: 'center',
            dataIndex: 'progress',
            customRender: (text) => {
              return filterDictTextByCache('customer_info_progress', text)
            }
          },
          {
            title: '阶段分类',
            align: 'center',
            dataIndex: 'stageType',
            customRender: (text) => {
              if (text === 1) {
                return '市场阶段'
              } else if (text === 2) {
                return '洽谈阶段'
              } else if (text === 3) {
                return '设计阶段'
              } else if (text === 4) {
                return '工程阶段'
              } else {
                return '维保阶段'
              }
            }
          },
          {
            title: '房屋面积',
            align: 'center',
            dataIndex: 'houseArea',
            customRender: function (text) {
              if (text != null && text != '') {
                return text + 'm²'
              }
            }
          },
          {
            title: '房屋户型',
            align: 'center',
            dataIndex: 'houseType',
            customRender: (text) => {
              return filterDictTextByCache('customer_info_house_type', text)
            }
          },
          {
            title: '量房时间',
            align: 'center',
            dataIndex: 'calculateTime'
          },
          {
            title: '添加时间',
            align: 'center',
            dataIndex: 'createTime'
          },
          {
            title: '创建人',
            align: 'center',
            dataIndex: 'createBy',
            fixed: 'right',
            width: 90,
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 147,
            scopedSlots: {
              customRender: 'action'
            },
          }
        ],
        settingColumns: [],
        queryParam: {},
        dataSource: [],
        currentStageType: 0,
        currentProgressValue: '',
        currentDateValue: '',   //选中的创建时间
        currentFollowDateValue: '',   //选中的跟进时间
        currentFactDateValue: '',   //选中的到店时间
        url: {
          list: '/ghCustomerInfo/list',
          delete: '/ghCustomerInfo/delete',
          deleteBatch: '/ghCustomerInfo/deleteBatch',
          exportXlsUrl: '/ghCustomerInfo/exportXls',
          importExcelUrl: '/ghCustomerInfo/importExcel',
          getItemsByDictCodeUrl: '/ghCustomerInfo/getItemsByDictCode',
          queryMouldByCode: '/ghImportMould/queryByCode',
          /*queryUserList: "/sys/user/allList",*/
          queryDepartTreeList: '/erp/user/selectDepartTreeList',
          queryUserList: '/erp/user/selectUserByDepartId',
          handoverCustomerUrl: '/ghCustomerInfo/handoverCustomer',
        },
        dictOptions: {},
        superFieldList: [],
        searchOptions: [],
        selectedRowKeys: [],
        selectedRows: [],
        createByData: [],    //创建人列表
        departListData: [],    //部门列表
        currentDepartId: '',  //当前所选部门
        currentOrgCode: '',   //当前所选部门编码
        dataFields: {
          title: 'departName',
          key: 'id',
          value: 'id',
          children: 'children'
        },

        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter: {
          column: 'createTime',
          order: 'desc',
        },
        showSearchPopupFlag: false,
      }
    },
    created() {
      let progressObj = JSON.parse(sessionStorage.getItem("progressKey"));
      if(progressObj){
        this.currentDateValue = progressObj.itemValue
      }

      let addDateObj = JSON.parse(sessionStorage.getItem("addDateKey"));
      if(addDateObj){
        this.currentDateValue = addDateObj.itemValue
      }

      let followDateObj = JSON.parse(sessionStorage.getItem("followDateKey"));
      if(followDateObj){
        this.currentFollowDateValue = followDateObj.itemValue
      }

      let factDateObj = JSON.parse(sessionStorage.getItem("factDateKey"));
      if(factDateObj){
        this.currentFactDateValue = factDateObj.itemValue
      }

      this.loadUserListData()
      this.initColumns()
      this.initProgressData()
      //this.initProgressData()
      //this.loadUserListData();
      this.loadDepartTreeListData()
    },
    beforeMount() {
      this.queryParam = this.customerSearch;
      this.currentDepartId = this.customerDepartId;
    },
    mounted() {
      initDictOptions('customer_info_customer_channel').then((res) => {
        if (res.success) {
          this.option2 = []
          this.option2 = [...[{text: "全部",value: "0"}],...res.result]
        }
      });
      this.loadData()
    },
    computed: {
      ...mapState(['customerSearch','customerDepartId','customerProgressKey']),
      tokenHeader() {
        let head = { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) }
        let tenantid = Vue.ls.get(TENANT_ID)
        if (tenantid) {
          head['tenant-id'] = tenantid
        }
        return head
      },
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
      },
    },
    methods: {
      ...mapMutations(['setCustomerSearch','clearCustomerSearch','setCustomerDepartId','setCustomerProgressKey']),

      changeProgress(i){
        let items = this.cacheProgressList[i]

        const { key, itemValue, itemText, value } = items
        this.currentProgressValue = itemValue
        let obj = {
          key,
          itemValue,
          itemText,
          value
        }
        sessionStorage.setItem("progressKey",JSON.stringify(obj));
        this.currentProgressValue = itemValue
        this.loadData(1)
      },
      changeAddDate(i){
        let item = this.addDateList[i]
        const { key, itemValue, itemText, value } = item
        this.currentDateValue = itemValue
        let obj = {
          key,
          itemValue,
          itemText,
          value
        }
        sessionStorage.setItem("addDateKey",JSON.stringify(obj));
        this.loadData(1)
      },
      changeFollow(i){
        let item = this.followDateList[i]
        const { key, itemValue, itemText, value } = item
        this.currentFollowDateValue = itemValue;
        let obj = {
          key,
          itemValue,
          itemText,
          value
        }
        sessionStorage.setItem("followDateKey",JSON.stringify(obj));
        this.loadData(1)
      },
      changeFact(i){
        let item = this.factDateList[i]
        const { key, itemValue, itemText } = item
        this.currentFactDateValue = itemValue;
        let obj = {
          key,
          itemValue,
          itemText
        }
        sessionStorage.setItem("factDateKey",JSON.stringify(obj));
        this.loadData(1)
      },
      onColSettingsChange(checkedValues) {
        let key = this.$route.name + ':colsettings'
        Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
        this.settingColumns = checkedValues
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (this.settingColumns.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols
      },
      initColumns() {
        //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
        let key = this.$route.name + ':colsettings'
        let colSettings = Vue.ls.get(key)
        if (colSettings == null || colSettings == undefined) {
          let allSettingColumns = []
          this.defColumns.forEach(function (item, i, array) {
            allSettingColumns.push(item.dataIndex)
          })
          this.settingColumns = allSettingColumns
          this.columns = this.defColumns
        } else {
          this.settingColumns = colSettings
          const cols = this.defColumns.filter(item => {
            if (item.key == 'rowIndex' || item.dataIndex == 'action') {
              return true
            }
            if (colSettings.includes(item.dataIndex)) {
              return true
            }
            return false
          })
          this.columns = cols
        }
      },
      changeStageType(i) {
        let value = this.option1[i*1].key
        this.currentStageType = value
        this.queryParam.stageType = value
        this.progressList = []
        // if (value != null) {
        //   this.loadData(1)
        // }
        if (value == 1) {
          for (let i = 0; i < this.cacheProgressList.length; i++) {
            if (i == 0) {
              this.progressList.push(this.cacheProgressList[i])
              this.currentProgressValue = this.cacheProgressList[i].itemValue
              this.loadData(1)
            }
            if (i >= 1 && i <= 5) {
              this.progressList.push(this.cacheProgressList[i])
            }
          }
        } else if (value == 3) {
          for (let i = 0; i < this.cacheProgressList.length; i++) {
            if (i == 0) {
              this.progressList.push(this.cacheProgressList[i])
              this.currentProgressValue = this.cacheProgressList[i].itemValue
              this.loadData(1)
            }
            if (i >= 6 && i <= 12) {
              this.progressList.push(this.cacheProgressList[i])
            }
          }
        } else if (value == 4) {
          for (let i = 0; i < this.cacheProgressList.length; i++) {
            if (i == 0) {
              this.progressList.push(this.cacheProgressList[i])
              this.currentProgressValue = this.cacheProgressList[i].itemValue
              this.loadData(1)
            }
            if (i >= 13 && i <= 43) {
              this.progressList.push(this.cacheProgressList[i])
            }
          }
        } else if (value == 5) {
          for (let i = 0; i < this.cacheProgressList.length; i++) {
            if (i == 0) {
              this.progressList.push(this.cacheProgressList[i])
              this.currentProgressValue = this.cacheProgressList[i].itemValue
              this.loadData(1)
            }
            if (i >= 44 && i <= 45) {
              this.progressList.push(this.cacheProgressList[i])
            }
          }
        } else {
          this.progressList = this.cacheProgressList
          for (let i = 0; i < this.progressList.length; i++) {
            if (i == 0) {
              this.currentProgressValue = this.progressList[i].itemValue
              this.loadData(1)
            } else {
            }
          }
        }
      },
      changeChannel(value) {
        if (value != 0){
          this.queryParam.customerChannel = value
        }else {
          delete this.queryParam.customerChannel;
        }
        this.loadData(1)
      },
      initProgressData() {
        getAction(this.url.getItemsByDictCodeUrl).then(res => {
          if (res.success) {
            let progressList = res.result.progressDictItemList;
            let addDateList = res.result.addDateList.slice(0,res.result.addDateList.length-1);
            let followDateList = res.result.followDateList.slice(0,res.result.followDateList.length-1);
            let factDateList = res.result.factDateList.slice(0,res.result.factDateList.length-1);

            let progressObj = JSON.parse(sessionStorage.getItem("progressKey"));
            if (progressObj != null){
              let obj = progressList.filter(item => item.key === progressObj.key);
              if (obj[0].key !== 'key0'){
                setTimeout(()=>{
                  this.value4 = obj[0].value
                },100)
              }
            }
            this.progressList = progressList;
            for(let i=0;i<this.progressList.length;i++){
              this.progressList[i].text = this.progressList[i].itemText
              this.progressList[i].value = i
            }
            this.cacheProgressList = progressList;
            let addDateObj = JSON.parse(sessionStorage.getItem("addDateKey"));
            if (addDateObj != null){
              let obj = addDateList.filter(item => item.key === addDateObj.key);
              if (obj[0].key !== 'key0'){
                setTimeout(()=>{
                  this.value5 = obj[0].value
                },100)
              }
            }
            for(let i=0;i<addDateList.length;i++){
              addDateList[i].text = addDateList[i].itemText
              addDateList[i].value = i
            }
            this.addDateList = addDateList;



            let followDateObj = JSON.parse(sessionStorage.getItem("followDateKey"));
            if (followDateObj != null){
              let obj = followDateList.filter(item => item.key === followDateObj.key);
              setTimeout(()=>{
                this.value6 = obj[0].value
              },100)
            }
            for(let i=0;i<followDateList.length;i++){
              followDateList[i].text = followDateList[i].itemText
              followDateList[i].value = i
            }
            this.followDateList = followDateList



            let factDateObj = JSON.parse(sessionStorage.getItem("factDateKey"));
            if (factDateObj != null){
              let obj = factDateList.filter(item => item.key === factDateObj.key);
              setTimeout(()=>{
                this.value7 = obj[0].value
              },100)
            }
            for(let i=0;i<factDateList.length;i++){
              factDateList[i].text = factDateList[i].itemText
              factDateList[i].value = i
            }
            this.factDateList = factDateList;
          }
        })
      },
      //下一页
      onLoadList(e){
        this.ipagination.current++
        this.loadData(this.ipagination.current)
      },
      loadData(arg) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.dataSource = []
          this.finished = false;
          this.ipagination.current = 1
        }
        let params = this.getQueryParams()//查询条件
        this.loading = true;
        if (this.currentProgressValue != null && this.currentProgressValue !== '' && this.currentProgressValue != 0) {
          params.progress = this.currentProgressValue
        }else {
          let progressObj = JSON.parse(sessionStorage.getItem("progressKey"));
          if (progressObj != null){
            params.progress = progressObj.itemValue;
          }
        }

        if (this.currentDateValue != null && this.currentDateValue !== '') {
          params.currentTime = this.currentDateValue
        }else {
          let addDateObj = JSON.parse(sessionStorage.getItem("addDateKey"));
          if (addDateObj != null){
            params.currentTime = addDateObj.itemValue;
          }
        }
        if (this.currentFollowDateValue != null && this.currentFollowDateValue !== '') {
          params.currentFollowTime = this.currentFollowDateValue
        }else {
          let followDateObj = JSON.parse(sessionStorage.getItem("followDateKey"));
          if (followDateObj != null){
            params.currentFollowTime = followDateObj.itemValue;
          }
        }
        if (this.currentFactDateValue != null && this.currentFactDateValue !== '') {
          params.currentFactTime = this.currentFactDateValue
        }else {
          let factDateObj = JSON.parse(sessionStorage.getItem("factDateKey"));
          if (factDateObj != null){
            params.currentFactTime = factDateObj.itemValue;
          }
        }
        params.departId = this.currentDepartId
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = [...this.dataSource, ...res.result.records]
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
          this.loading = false
          if(res.result.records.length<10){
            this.finished = true;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      handleInfoDetail(id, name) {
        this.$router.push({ path: '/infoTab', query: { id: id, name: name } });
        this.setCustomerSearch(this.queryParam)
        this.setCustomerDepartId(this.currentDepartId)
      },
      searchQuery() {
        this.selectedRowKeys = []
        this.selectedRows = []
        this.showSearchPopupFlag = false
        if (this.queryParam.name || this.queryParam.phone || this.queryParam.address){
          this.showConditionFlag = true
        }
        this.setCustomerSearch(this.queryParam)
        this.setCustomerDepartId(this.currentDepartId)
        this.loadData(1)
      },
      resetSearch() {
        this.value1 = 0
        this.value2 = 0
        this.value4 = 0
        this.value5 = 0
        this.value6 = 0
        this.value7 = 0
        this.selectedRowKeys = []
        this.selectedRows = []
        this.showSearchPopupFlag = false
        this.showConditionFlag = false
        this.clearCustomerSearch();
        sessionStorage.removeItem("progressKey");
        sessionStorage.removeItem("addDateKey");
        sessionStorage.removeItem("followDateKey");
        sessionStorage.removeItem("factDateKey");
        this.currentProgressValue = '';
        this.currentDateValue = '';
        this.currentFollowDateValue = '';
        this.currentFactDateValue = '';

        this.queryParam = {}
        this.currentDepartId = ''
        this.progressList = []
        this.progressList = this.cacheProgressList
        this.loadData(1)
      },
      //下载模板
      downloadMould(value) {
        getAction(this.url.queryMouldByCode, { code: value })
          .then(res => {
            if (res.success) {
              this.obj = res.result
              window.location = this.obj.mouldUrl + '?response-content-type=application/octet-stream'
            }
          })
      },
      //客户交接
      handoverCustomer() {
        if (this.selectedRows.length <= 0) {
          this.$message.error('请先选择需要交接的客户')
          return
        }
        this.$refs.SelectUserModal.title = '选择用户'
        this.$refs.SelectUserModal.handoverFlag = true
        this.$refs.SelectUserModal.add()
      },
      selectUserOk(obj) {
        let that = this
        let params = {}
        params.customerInfoList = this.selectedRows
        params.sysUser = obj
        that.loading = true
        postAction(that.url.handoverCustomerUrl, params).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.loadData(1)
          } else {
            that.$message.warning(res.message)
          }
        }).finally(() => {
          that.loading = false
          that.selectedRowKeys = [];
          that.selectedRows = [];
        })
      },

      onSelectAll(selected, selectedRows, changeRows) {
        if (selected) {
          let rows = [...selectedRows]
          this.selectedRows = this.selectedRows.concat(rows)
        } else {
          changeRows.forEach(item => {
            const delIndex = this.selectedRows.findIndex((val) => {
              return val.id === item.id
            })
            this.selectedRows.splice(delIndex, 1)
          })
        }
      },
      onSelect(record, selected) {
        if (selected) {
          this.selectedRows.push(record)
        } else {
          const delIndex = this.selectedRows.findIndex((val) => {
            return val.id === record.id
          })
          this.selectedRows.splice(delIndex, 1)
        }
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },
      filterOptionCreateBy(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },
      filterOptionDepart(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },
      changeCreateBy(value) {
        this.loadData(1)
      },
      changeDepart(value) {
        this.currentDepartId = value
        this.loadUserListData()
        this.loadData(1)
      },
      //加载用户列表
      loadUserListData() {
        //this.currentDepartId
        getAction(this.url.queryUserList, { departId: "" }).then((res) => {
          if (res.success) {
            this.createByData = res.result.records || res.result
            let list = res.result.records || res.result
            this.option3 = [{
              text: "全部",
              value: ""
            }]
            for(let i=0;i<list.length;i++){
              this.option3.push({
                text: list[i].realname,
                value: list[i].realname
              })
            }
          }
        })
      },
      //加载部门树形列表
      loadDepartTreeListData() {
        getAction(this.url.queryDepartTreeList).then((res) => {
          if (res.success) {
            this.departListData = res.result.records || res.result
          }
        })
      },
      //表格行点击事件
      setRow(record) {
        return {
          on: {
            click: () => {
              let flag = false
              let keys = []
              keys = this.selectedRowKeys
              if (keys.indexOf(record.id) >= 0) {
                flag = true
              }
              if (flag) {
                keys.splice(keys.findIndex(item => item === record.id), 1)
                this.selectedRows.splice(this.selectedRows.findIndex(item => item === record.id), 1)
              } else {
                keys.push(record.id)
                this.selectedRows.push(record)
              }
            }
          }
        }
      },

      handleTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
        }
        this.ipagination = pagination
        this.loadData()
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        this.loadData()
        //清空列表选中
        this.onClearSelected()
      },
      handleExportXls(fileName) {
        if (!fileName || typeof fileName != 'string') {
          fileName = '导出文件'
        }
        let param = this.getQueryParams()
        if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
          param['selections'] = this.selectedRowKeys.join(',')
        }
        //console.log("导出参数",param)
        downFile(this.url.exportXlsUrl, param).then((data) => {
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
      },

      /* 导入 */
      handleImportExcel(info) {
        this.loading = true
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList)
        }
        if (info.file.status === 'done') {
          this.loading = false
          if (info.file.response.success) {
            // this.$message.success(`${info.file.name} 文件上传成功`);
            if (info.file.response.code === 201) {
              let { message, result: { msg, fileUrl, fileName } } = info.file.response
              let href = window._CONFIG['domianURL'] + fileUrl
              this.$warning({
                  title: message,
                  content: ( < div >
                    < span > { msg } < /span><br/ >
                    < span > 具体详情请 < a href = { href } target = '_blank' download = { fileName } > 点击下载 < /a> </span >
                < /div>
              )
            })
            } else {
              this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
            }
            this.loadData()
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}.`)
          }
        } else if (info.file.status === 'error') {
          this.loading = false
          if (info.file.response.status === 500) {
            let data = info.file.response
            const token = Vue.ls.get(ACCESS_TOKEN)
            if (token && data.message.includes('Token失效')) {
              this.$error({
                title: '登录已过期',
                content: '很抱歉，登录已过期，请重新登录',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                  store.dispatch('Logout').then(() => {
                    Vue.ls.remove(ACCESS_TOKEN)
                    window.location.reload()
                  })
                }
              })
            }
          } else {
            this.$message.error(`文件上传失败: ${info.file.msg} `)
          }
        }
      },
      handleAdd: function () {
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.disableSubmit = false
      },
      batchDel: function () {
        if (!this.url.deleteBatch) {
          this.$message.error('请设置url.deleteBatch属性!')
          return
        }
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！')
          return
        } else {
          let ids = ''
          for (let a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ','
          }
          let that = this
          this.$confirm({
            title: '确认删除',
            content: '是否删除选中数据?',
            onOk: function () {
              that.loading = true
              deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
                if (res.success) {
                  //重新计算分页问题
                  that.reCalculatePage(that.selectedRowKeys.length)
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.loading = false
              })
            }
          })
        }
      },
      getQueryParams() {
        //获取查询条件
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        let param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField() {
        //TODO 字段权限控制
        let str = 'id,'
        this.columns.forEach(function (value) {
          str += ',' + value.dataIndex
        })
        return str
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      reCalculatePage(count) {
        //总数量-count
        let total = this.ipagination.total - count
        //获取删除后的分页数
        let currentIndex = Math.ceil(total / this.ipagination.pageSize)
        //删除后的分页数<所在当前页
        if (currentIndex < this.ipagination.current) {
          this.ipagination.current = currentIndex
        }
      },
      showSearchPopup(){
        this.showSearchPopupFlag = true
      },
      checkClick(record,e){
        if (e.target.checked){
          this.selectedRows.push(record);
          this.selectedRowKeys.push(record.id)
        }else {
          const delIndex1 = this.selectedRows.findIndex((val) => {
            return val.id === record.id;
          })
          const delIndex2 = this.selectedRowKeys.findIndex((val) => {
            return val === record.id;
          })
          this.selectedRows.splice(delIndex1,1)
          this.selectedRowKeys.splice(delIndex2,1)
        }
      },
    }
  }
</script>

<style scoped lang="less">
  @import '~@assets/less/common.less';
  .van-dropdown-menu{
    width: 100vw;
    overflow: scroll;
    border-bottom: 1px solid #d6d3d3;
  }
  .van-dropdown-menu /deep/ .van-dropdown-menu__bar{
    width: max-content;
  }
  .van-dropdown-menu /deep/ .van-dropdown-menu__item{
    width: 100px;
  }
  .select-pk{
    display:flex;
    align-items:center;
    margin:10px 0;
    &>span{
      font-weight: bold;
    }
    &-text{
      width: calc(100% - 6em);
      height: 30px;
      text-indent: 1em;
      line-height: 28px;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
    }
  }
  .ant-card /deep/ .ant-card-body{
    padding-top:10px !important;
  }
  .ant-form-item{
    margin-bottom: 5px !important;
  }
  .table-operator{
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    .ant-btn{
      margin: 0 !important;
    }
  }

  .list{
    overflow-y: scroll;
    height:calc(100vh - 227px);
  }
  ::-webkit-scrollbar {
    display: none;
  }
  .customer-list{
    /*display: flex;*/
    align-items: center;
    border-top: 1px solid #d9d9d9;
    height: 60px;
    .name{
      font-size: 13px;
      color: #161616;
      line-height: normal;
      margin-top: 10px;
    }
    .contact{
      font-size: 12px;
      color: #a39f9f;
    }
  }
</style>